package com.delivery.www.dao.DaoImpl;

import com.delivery.www.dao.BaseDao;
import com.delivery.www.dao.CartDishDao;
import com.delivery.www.po.CartDish;
import com.delivery.www.po.Dish;
import com.delivery.www.util.JdbcUtils;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 12970
 */
public class CartDishDaoImpl implements CartDishDao {
    @Override
    public int addCartDish(int cartId, int dishId) {
        Connection connection = JdbcUtils.getConnection();
        Object[] params = {cartId, dishId};
        String sql = "insert into cart_dish(cart_id,dish_id) values(?,?)";
        int i = 0;
        if (connection != null) {
            i = BaseDao.executeUpdate(connection, sql, params);
            JdbcUtils.closeResource(connection, null, null);
        }
        return i;
    }

    @Override
    public List<List<Dish>> getCartAllDish(List<List<Integer>> list) {
        Connection connection = JdbcUtils.getConnection();
        List<Dish> dishes;
        List<List<Dish>> lists = new ArrayList<>();
        StringBuilder sql2 = new StringBuilder();
        sql2.append("select d.dish_id,dish_name,d.store_id,price,`describe`,s.store_name from dish d left join");
        sql2.append(" store s on d.store_id = s.store_id");
        sql2.append(" where d.dish_id = ?");
        for (List<Integer> integers : list) {
            dishes = new ArrayList<>();
            for (Integer integer : integers) {
                Dish dish = BaseDao.getForOne(connection, Dish.class, sql2.toString(), integer);
                dishes.add(dish);
            }
            if (dishes.size() != 0) {
                lists.add(dishes);
            }
        }
        JdbcUtils.closeResource(connection, null, null);
        return lists;
    }

    @Override
    public List<List<Integer>> getCartDish(List<Integer> cartIds) {
        Connection connection = JdbcUtils.getConnection();
        List<Integer> integers;
        List<List<Integer>> list = new ArrayList<>();
        Object[] objects = cartIds.toArray();
        String sql = "select cart_dish_id,cart_id,dish_id from cart_dish where cart_id = ?";
        for (Object param : objects) {
            List<CartDish> cartDishes = BaseDao.getList(connection, CartDish.class, sql, param);
            if (cartDishes != null) {
                integers = new ArrayList<>();
                for (CartDish cartDish : cartDishes) {
                    Integer dishId = cartDish.getDishId();
                    integers.add(dishId);
                }
                if (integers.size() != 0) {
                    list.add(integers);
                }
            }
        }
        return list;
    }
}
